/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia.mail;

import br.com.jr2tecnologia.SMSUtil;
import javax.mail.Address;
import javax.mail.internet.InternetAddress;

/**
 *
 * @author ronildo
 */
public class SMSMail {

    private String from;
    private String to;
    private String subject;
    private String message;
    private String phone;

    public SMSMail() {
    }

    public String getFrom() {
        return from;
    }
    public String getMessage() {
        return message;
    }
    public String getSubject() {
        return subject;
    }
    public String getTo() {
        return to;
    }
    public String getPhone() {
        return phone;
    }

    public void setFrom(Address address[]) {
        this.from = parseAddress(address);
    }
    public void setMessage(Object arg) {
        this.message = parseMessage(arg);
    }
    public void setSubject(String subject) {
        this.subject = subject;
    }
    public void setTo(String address) {
        this.to = parseAddress(address);
    }
    public void setPhone(String address) {
        this.phone = parsePhone(to);
    }
    
    private static String parsePhone(String arg){
        arg = arg.replaceAll("\"", "");
        int index = arg.indexOf("@");
        String phone = arg.substring( index > 12 ? index-12 : 0, index );
        return SMSUtil.arrangesPhone(phone);
    }

    private static String parseAddress(String arg){
        String mail[] = arg.split(" ");
        for(int i = 0; i < mail.length; i++)
            if(mail[i].indexOf("@") != -1 && mail[i].indexOf(".") != -1){
                String aux =  mail[i];
                aux = aux.replaceAll("<", "");
                aux = aux.replaceAll(">", "");
                return aux;
            }
        return null;
    }

    private static String parseAddress(Address address[]){
        String arg = InternetAddress.toString(address);
        String mail[] = arg.split(" ");
        for(int i = 0; i < mail.length; i++)
            if(mail[i].indexOf("@") != -1 && mail[i].indexOf(".") != -1){
                String aux =  mail[i];
                aux = aux.replaceAll("<", "");
                aux = aux.replaceAll(">", "");
                return aux;
            }
        return null;
    }

    private static String parseMessage(Object object){
        String msg = object.toString();
        if(msg.lastIndexOf("--") != -1)
            return msg.substring(0, msg.lastIndexOf("--"));
        else
            return msg;
    }

    @Override
    public String toString() {
        return "from:"+from+" - to:"+to+" - subject:"+subject+" \nmessage:"+message;
    }
}
